package com.zcsy.commons.util;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
/**
 * 提取相同类型Bean中不同的属性
 * @author YHC
 * @version 2015年5月27日
 * @see ComparaBeanUtil
 * @since
 */
public class ComparaBeanUtil {
    /**
     * Description: 提取相同类型Bean中不同的属性<br>
     * 1、获取相同类型bean中不同的属性
     * @param oldBean 改变前的对象
     * @param newBean 改变后的对象
     * @return Map<String,String>
     * 第一个String是改变的属性名
     * 第二个String是改变的具体内容
     */
    public static Map<String,String> compareBean(Object oldBean,Object newBean) {
        
        Class<?> OldBean = oldBean.getClass();
        Class<?> NewBean = newBean.getClass();
        Field[] oldFields = OldBean.getDeclaredFields();
        Field[] newFields = NewBean.getDeclaredFields();
        Field oldField = null;
        Field newField = null;
        Map<String,String> diff = new HashMap<String,String>();
        for(int i = 0; i < oldFields.length; i++) {
            try {
            	oldField = oldFields[i];
            	newField = newFields[i];
            	oldField.setAccessible(true);
            	newField.setAccessible(true);
                String oldValue = oldField.get(oldBean).toString();
                String newValue = oldField.get(newBean).toString();
                if(!oldValue.equals(newValue)) {
                    diff.put(oldField.getName(),"由"+oldValue+"改为"+newValue+";");
                }
            } catch (Exception e) {
            }
        }
        return diff;
    }
}
